<?php
/**
 * projectname:gdu_cms2 
 * author:senman
 * time:2017/8/9 13:13
 */

namespace app\admin\controller;

use app\admin\builder\AdminConfigBuilder;
use app\admin\builder\AdminListBuilder;
use think\Db;
use think\Exception;
use think\Request;
use think\Validate;


class Rule extends Auth
{
    protected $user_model;
    protected $group_model;
    protected $access_model;
    protected $user_id;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->auth();
        $this->group_model = model('Group');
        $this->user_model = model('User');
        $this->access_model = model('Access');
        $this->user_id = session('user_id');
    }


    /**
     * @describe  功能列表
     * @return mixed
     */
    public function ruleList()
    {
        $data = $this->rule_model->select();
        if ($data) {
            foreach ($data as $k => $v) {
                if ($v['pid'] > 0) {
                    $p_name = $this->rule_model->where(['id' => $v['pid']])->field('name')->find();
                    if ($p_name) {
                        $data[$k]['p_name'] = $p_name['name'];
                    } else {
                        $data[$k]['p_name'] = "";
                    }
                } else {
                    $data[$k]['p_name'] = "";
                }
                if ($v['status'] == 1) {
                    $data[$k]['status'] = 0;
                } else {
                    $data[$k]['status'] = 1;
                }
            }
        }

        $builderlist = new AdminListBuilder();
        $builderlist->title('权限管理')->suggest('功能列表');
        $builderlist->keyText('name', '名称');
        $builderlist->keyText('url', '地址');
        $builderlist->keyText('p_name', '父级');
        $builderlist->keyText('create_time', '创建时间');
        $builderlist->keyText('update_time', '更新时间');

        if (checkAuth('admin/rule/add')) {
            $builderlist->buttonNew('添加', '', url('admin/rule/add'));
        }
        if (checkAuth('admin/rule/delete')) {
            $builderlist->buttonDelete('批量删除', '', url('admin/rule/delete'));
        }
        if (checkAuth('admin/rule/delete')) {
            $builderlist->keyDoActionPost(url('admin/rule/delete'), '删除', 'btn-danger');
        }
        if (checkAuth('admin/rule/update')) {
            $builderlist->keyDoActionLink(url('admin/rule/update'), '编辑', 'btn-primary');
        }
        if (checkAuth('admin/rule/changeState')) {
            $builderlist->keyDoActionPostTextChange(url('admin/rule/changeState'), '启用', '禁用', 'status');
        }

        $builderlist->data($data);
        //写日志
        Log::writeLog("查看功能列表");
        return $builderlist->displayList();
    }

    /**
     * 新增
     * @return mixed|\think\response\Json
     */
    public function add()
    {
        if ($this->request->isPost()) {

            $param = $this->request->post();
            $param['url'] = strtolower($param['url']);
            $validate = validate('Rule');
            if(!$validate->scene('add')->check($param)){
                return json(['status'=>0,'info'=>lang($validate->getError())]);
            }
            if (model('Rule')->save($param)) {
                //写日志
                Log::writeLog("新增功能:" . $param['name']);
                $this->send(1, lang('OPERATE_SUCCESS'), url('admin/rule/ruleList'));
            } else {
                return $this->send(0, lang('OPERATE_FAILE'));
            }

        } else {
            $builder = new AdminConfigBuilder();
            $menus = model('Rule')->getTopMenus();
            $builder->title('权限管理')->suggest('新增')->formsubmit('功能新增');
            $builder->keyText('name', '名称')->keyText('url', '地址');
            $builder->keyText('icon', '图标名称');
            $builder->keySelect('pid', '选择上级目录菜单', '', $menus);
            $builder->keyText('sort', '排序', '');
            $builder->keySelect('hidden', '是否隐藏', '', ['0' => '显示', '1' => '隐藏']);
            $builder->keySelect('status', '是否启用', '', ['0' => '启用', '1' => '禁用']);
            $builder->buttonSubmit(url('admin/rule/add'))->buttonBack();
            //写日志
            Log::writeLog("进入功能新增页面");
            return $builder->displayConfig();
        }
    }

    /**
     * 删除
     * @return \think\response\Json
     */
    public function delete()
    {
        $ids = $this->request->post('id') ? $this->request->post('id') : explode(',', $this->request->post('ids'));
        if (model('Rule')->delMenus($ids)) {
            //写日志
            Log::writeLog("删除功能点");
            return $this->send(1, lang('OPERATE_SUCCESS'), url('admin/rule/ruleList'));
        } else {
            return $this->send(0, lang('OPERATE_FAILE'));
        }
    }

    /**
     * 更新
     * @return mixed|\think\response\Json
     */
    public function update()
    {
        if ($this->request->isPost()) {
            $param = $this->request->post();
            $param['url'] = strtolower($param['url']);
            $validate = validate('Rule');
            if(!$validate->scene('add')->check($param)){
                return json(['status'=>0,'info'=>lang($validate->getError())]);
            }
            if (model('Rule')->isUpdate(true)->save($param, ['id' => $param['id']])) {
                //写日志
                Log::writeLog("更改功能");
                return $this->send(1, lang('OPERATE_SUCCESS'), url('admin/rule/ruleList'));
            }
            return $this->send(0, lang('OPERATE_FAILE'));
        } else {
            $id = $this->request->get('id');
            $data = model('Rule')->getMenuById($id);
            $builder = new AdminConfigBuilder();

            $menus = model('Rule')->getTopMenus();
            $builder->title('权限管理')->suggest('修改')->formsubmit('功能修改');
            $builder->keyText('name', '名称')->keyText('url', '地址');
            $builder->keyText('icon', '图标名称');
            $builder->keySelect('pid', '选择上级目录菜单', '', $menus);
            $builder->keyText('sort', '排序', '从小到大排序');

            $builder->keySelect('hidden', '是否隐藏', '', ['0' => '显示', '1' => '隐藏']);
            $builder->keySelect('status', '是否启用', '', ['0' => '启用', '1' => '禁用']);
            $builder->keyHidden('id');
            $builder->buttonSubmit()->buttonBack();
            $builder->data($data);
            //写日志
            Log::writeLog("查看更改功能页面");
            return $builder->displayConfig();
        }
    }

    /**
     * 修改状态
     */
    public function changeState()
    {
        $input = $this->request->post();
        $id = $input['id'];
        if ($input['publish'] == "publish") {
            $status = 0;//启用
        } else {
            $status = 1;//禁用
        }

        Db::startTrans();
        try {
            $rule_rs = $this->rule_model->where(["id" => $id])->field('pid')->find();

            if ($rule_rs) {
                if ($rule_rs['pid'] > 0) {//pid就是根节点
                    $pid = $rule_rs['pid'];
                } else {//本身就是根节点
                    $pid = $id;
                }

                $rules = $this->rule_model->where(['pid' => $pid])->field('id')->select();
                if ($rules) {
                    if ($status == 1) {
                        foreach ($rules as $k => $v) {
                            $this->rule_model->where(['id' => $v['id']])->update(['status' => $status]);
                        }

                    }
                }


                $condition = [];
                $condition['id'] = $id;
                $this->rule_model->where($condition)->update(['status' => $status]);
            } else {
                Db::rollback();
                return json(['status' => 0, 'info' => lang('OPERATE_FAILE')]);
            }
            //写日志
            Log::writeLog("更改功能点状态");
            DB::commit();
            return json(['status' => 1, 'info' => lang('OPERATE_SUCCESS'), 'url' => url('admin/rule/ruleList')]);

        } catch (Exception $exception) {
            Db::rollback();
            return json(['status' => 0, 'info' => lang('OPERATE_FAILE')]);
        }


    }

}